package com.panghl.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Author panghl
 * @Date 2022/2/27
 * @Description TODO
 **/
@Configuration
@MapperScan(basePackages = "com.panghl.test02", sqlSessionFactoryRef = "test02SqlSessionFactory")
public class DataSource2Config {

    /**
     * 配置test02数据库
     *
     * @return
     */
    @Bean(name = "test02DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test02")
    public DataSource test02DataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * test02 sql会话工厂
     */
    @Bean(name = "test02SqlSessionFactory")
    public SqlSessionFactory test02SqlSessionFactory(@Qualifier("test02DataSource") DataSource test02DataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(test02DataSource);
        //bean.setMapperLocations(
        //        new PathMatchingResourcePatternResolver().getResource("classpath:mapping/test/*Mapper.xml")
        //);
        return bean.getObject();
    }

    /**
     * test02 事务管理器
     */
    @Bean(name = "test02DataSourceTransactionManager")
    public DataSourceTransactionManager test02DataSourceTransactionManager(@Qualifier("test02DataSource") DataSource test02DataSource) {
        return new DataSourceTransactionManager(test02DataSource);
    }

    @Bean(name = "test02SqlSessionTemplate")
    public SqlSessionTemplate test02SqlSessionTemplate(@Qualifier("test02SqlSessionFactory") SqlSessionFactory test02SqlSessionFactory) {
        return new SqlSessionTemplate(test02SqlSessionFactory);
    }

}
